package cn.may.controller;

import cn.may.utils.UploadUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

/**
 * 文件上传
 *
 * @author mayuanbao
 * @date 2019-06-06 14:23
 */
@Controller
public class UploadController {
    private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

    /**
     * 单文件上传
     *
     * @return string
     */
    @GetMapping("/upload")
    public String upload() {
        return "upload.html";
    }

    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws FileNotFoundException {
        // 设置文件存储路径
        String filePath = ResourceUtils.getURL("classpath:").getPath() + "/static/upload/";
        return UploadUtil.upload(file, filePath);
    }

    /**
     * 多文件上传
     *
     * @return string
     */
    @GetMapping("/multiUpload")
    public String multiUpload() {
        return "multiUpload.html";
    }

    /*@PostMapping("/multiUpload")
    @ResponseBody
    public String multiUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
        String filePath = "F:/";
        for (int i = 0; i < files.size(); i++) {
            MultipartFile file = files.get(i);
            if (file.isEmpty()) {
                return "第 " + (i + 1) + " 个文件上传失败";
            }
            String fileName = file.getOriginalFilename();
            File dest = new File(filePath + fileName);
            try {
                file.transferTo(dest);
                logger.info("第 " + (i + 1) + "个文件上传成功");
            } catch (IOException e) {
                logger.error(e.toString(), e);
                return "第 " + (i + 1) + "个文件上传失败";
            }
        }
        return "上传成功";
    }*/

    @PostMapping("/multiUpload")
    @ResponseBody
    public Map<String, String> multiUpload(@RequestParam("file") List<MultipartFile> files) throws FileNotFoundException {
        String filePath = ResourceUtils.getURL("classpath:").getPath() + "/static/upload/";
        return UploadUtil.multiUpload(files, filePath);
    }
}
